import router from './router';
import NProgress from 'nprogress';
import 'nprogress/nprogress.css';
import { getToken } from '@/utils/auth';
import { isPathMatch } from '@/utils/validate';
import { useSettingsStore } from '@/store/modules/settings';

NProgress.configure({ showSpinner: false });
const whiteList = ['/login', '/register', '/','/about','/news' ];

const isWhiteList = (path: string) => {
  return whiteList.some(pattern => isPathMatch(pattern, path))
}

router.beforeEach(async (to, from, next) => {
  NProgress.start();
  if (getToken()) {
    to.meta.title && useSettingsStore().setTitle(to.meta.title as string);
    next()
  } else {
    // 没有token
    if (isWhiteList(to.path)) {
      // 在免登录白名单，直接进入
      next();
    } else {
      next({ path: '/login' });
    }
  }
});

router.afterEach(() => {
  NProgress.done();
});
